"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { ArrowLeft, AlertCircle, CheckCircle2, Copy, Eye, EyeOff } from "lucide-react"
import { useSettings } from "@/contexts/settings-context"

export default function SettingsPage() {
  const router = useRouter()
  const { apiKey, setApiKey, clearApiKey } = useSettings()
  const [inputApiKey, setInputApiKey] = useState("")
  const [showApiKey, setShowApiKey] = useState(false)
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null)
  const [copied, setCopied] = useState(false)

  // 初始化输入框的值
  useEffect(() => {
    setInputApiKey(apiKey)
  }, [apiKey])

  const handleSave = () => {
    try {
      // 简单验证API密钥格式
      if (inputApiKey && inputApiKey.length < 10) {
        setMessage({ type: "error", text: "API密钥格式似乎不正确，请检查后重试" })
        return
      }

      setApiKey(inputApiKey)
      setMessage({ type: "success", text: "API密钥已保存" })

      // 3秒后清除消息
      setTimeout(() => {
        setMessage(null)
      }, 3000)
    } catch (error) {
      setMessage({ type: "error", text: "保存API密钥时出错" })
    }
  }

  const handleClear = () => {
    clearApiKey()
    setInputApiKey("")
    setMessage({ type: "success", text: "API密钥已清除" })

    // 3秒后清除消息
    setTimeout(() => {
      setMessage(null)
    }, 3000)
  }

  const handleCopy = () => {
    if (apiKey) {
      navigator.clipboard.writeText(apiKey)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  const toggleShowApiKey = () => {
    setShowApiKey(!showApiKey)
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-sky-100 to-blue-50 p-4 md:p-8">
      <div className="max-w-2xl mx-auto">
        <Button variant="ghost" className="mb-6" onClick={() => router.push("/")}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回天气预报
        </Button>

        <Card>
          <CardHeader>
            <CardTitle className="text-2xl">API设置</CardTitle>
            <CardDescription>设置您的OpenWeather API密钥以获取天气数据</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {message && (
              <Alert variant={message.type === "success" ? "default" : "destructive"}>
                {message.type === "success" ? (
                  <CheckCircle2 className="h-4 w-4" />
                ) : (
                  <AlertCircle className="h-4 w-4" />
                )}
                <AlertDescription>{message.text}</AlertDescription>
              </Alert>
            )}

            <div className="space-y-2">
              <h3 className="text-sm font-medium">如何获取OpenWeather API密钥</h3>
              <ol className="list-decimal list-inside text-sm text-gray-600 space-y-1">
                <li>
                  访问{" "}
                  <a
                    href="https://openweathermap.org/api"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:underline"
                  >
                    OpenWeather API
                  </a>{" "}
                  网站
                </li>
                <li>注册一个账号或登录</li>
                <li>在个人资料页面找到"API密钥"选项卡</li>
                <li>复制您的API密钥</li>
                <li>粘贴到下面的输入框中</li>
              </ol>
            </div>

            <div className="space-y-2">
              <label htmlFor="api-key" className="text-sm font-medium">
                OpenWeather API密钥
              </label>
              <div className="flex">
                <Input
                  id="api-key"
                  type={showApiKey ? "text" : "password"}
                  value={inputApiKey}
                  onChange={(e) => setInputApiKey(e.target.value)}
                  placeholder="输入您的API密钥"
                  className="flex-1"
                />
                <Button variant="outline" size="icon" onClick={toggleShowApiKey} className="ml-2" type="button">
                  {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </Button>
              </div>
            </div>

            {apiKey && (
              <div className="flex items-center space-x-2">
                <span className="text-sm text-gray-500">当前已保存API密钥</span>
                <Button variant="outline" size="sm" onClick={handleCopy} className="h-7 px-2">
                  <Copy className="h-3.5 w-3.5 mr-1" />
                  {copied ? "已复制" : "复制"}
                </Button>
              </div>
            )}

            <div className="text-sm text-gray-500">
              <p>注意：API密钥将保存在您的浏览器本地存储中，不会发送到我们的服务器。</p>
              <p>新注册的API密钥可能需要几小时才能激活。</p>
            </div>
          </CardContent>
          <CardFooter className="flex justify-between">
            <Button variant="outline" onClick={handleClear}>
              清除API密钥
            </Button>
            <Button onClick={handleSave}>保存API密钥</Button>
          </CardFooter>
        </Card>
      </div>
    </div>
  )
}
